package com.example.coursedesign.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
//import android.widget.CardView;

import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;

import com.example.coursedesign.R;
import com.example.coursedesign.databinding.FragmentHomeBinding;
import com.example.coursedesign.ui.home.adapter.VideoAdapter;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment implements VideoAdapter.OnItemClickListener {

    private FragmentHomeBinding binding;
    private Handler handler;
    private Runnable runnable;
    private RecyclerView recyclerView; // RecyclerView 用于显示视频
    private VideoAdapter videoAdapter; // 视频适配器

    // 定义为类级别的成员变量
    private List<String> videoPaths = new ArrayList<>();
    private List<Integer> thumbnailIds = new ArrayList<>();
    private List<String> descriptions = new ArrayList<>();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        HomeViewModel homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        // 初始化轮播图
        ViewPager2 viewPager = binding.viewPager;
        List<Integer> imageResources = new ArrayList<>();
        imageResources.add(R.drawable.img1);
        imageResources.add(R.drawable.img2);
        imageResources.add(R.drawable.img3);

        CarouselAdapter adapter = new CarouselAdapter(requireContext(), imageResources);
        viewPager.setAdapter(adapter);

        // 设置自动翻页
        handler = new Handler(Looper.getMainLooper());
        runnable = new Runnable() {
            @Override
            public void run() {
                int currentItem = viewPager.getCurrentItem();
                int totalItems = adapter.getItemCount();
                if (currentItem < totalItems - 1) {
                    viewPager.setCurrentItem(currentItem + 1, true);
                } else {
                    viewPager.setCurrentItem(0, true);
                }
                handler.postDelayed(this, 3000); // 每 3 秒钟执行一次
            }
        };

        // 开始自动翻页
        handler.postDelayed(runnable, 3000);

        // 初始化 RecyclerView 和适配器
        recyclerView = binding.recyclerView;
        try {
            initializeVideoList();
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }


        CardView cardViewData = binding.cardViewData;
        cardViewData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), HealthDataActivity.class);
                startActivity(intent);
            }
        });


        CardView cardViewMedicine = binding.cardViewMedicine; // 根据你的 ID 获取 CardView
        cardViewMedicine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), medicineRemind.class);
                startActivity(intent);
            }
        });

        CardView cardViewMeridian = binding.cardViewStorage; // 根据你的 ID 获取 CardView
        cardViewMeridian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), searchMedicine.class);
                startActivity(intent);
            }
        });

        return root;
    }

    // 初始化视频列表和适配器
    private void initializeVideoList() throws NoSuchFieldException, IllegalAccessException {
        // 清空之前的列表数据，以防重复添加
        videoPaths.clear();
        thumbnailIds.clear();
        descriptions.clear();

        // 添加视频路径和对应缩略图资源
        addVideo("baduanjin", R.drawable.bdj, "健身气功——八段锦");
        addVideo("mawangdui", R.drawable.mwd, "跟练马王堆导引术");
        addVideo("v1", R.drawable.v1, "补气血，养气血");
        addVideo("mawangdui", R.drawable.v2, "四肢重，体内湿气多，就练这个动作");
        addVideo("mawangdui", R.drawable.v3, "祛湿排毒——文式易筋经");
        addVideo("mawangdui", R.drawable.v4, "健身气功——五禽戏完整口令版");
        addVideo("mawangdui", R.drawable.v5, "健身气功——易筋经标准版");
        addVideo("mawangdui", R.drawable.v6, "24式太极拳——呼吸导引跟练版");

        if (videoPaths.size() != thumbnailIds.size() || videoPaths.size() != descriptions.size()) {
            throw new IllegalStateException("视频路径、缩略图和描述列表的大小不一致");
        }
        videoAdapter = new VideoAdapter(requireContext(), videoPaths, thumbnailIds, descriptions);
        videoAdapter.setOnItemClickListener(this);

        // 使用 GridLayoutManager 设置每行两个视频
        recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 2));
        recyclerView.setAdapter(videoAdapter);
    }

    private void addVideo(String videoResourceName, int thumbnailId, String description) throws NoSuchFieldException, IllegalAccessException {
        videoPaths.add("android.resource://" + requireContext().getPackageName() + "/" + R.raw.class.getField(videoResourceName).get(null));
        thumbnailIds.add(thumbnailId);
        descriptions.add(description);
    }

    @Override
    public void onItemClick(int position) {
        // 启动VideoDetail Activity并传递视频信息
        Intent intent = new Intent(getActivity(), VideoDetail.class);
        intent.putExtra("videoPath", videoPaths.get(position));
        intent.putExtra("thumbnailId", thumbnailIds.get(position));
        intent.putExtra("description", descriptions.get(position));
        startActivity(intent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 停止自动翻页
        if (handler != null && runnable != null) {
            handler.removeCallbacks(runnable);
        }
        binding = null;
    }
}